package giit.computerbase.util;

/**
 * This class is for come up with get hash value<br>
 * User: tum0r
 * Package Name: tum0r.password
 * Time: 2018/10/28 Sunday 17:54:04
 */

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Hash {

    public static final String MD2 = "md2";
    public static final String MD5 = "md5";
    public static final String SHA1 = "sha-1";
    public static final String SHA224 = "sha-224";
    public static final String SHA256 = "sha-256";
    public static final String SHA384 = "sha-384";
    public static final String SHA512 = "sha-512";

    /**
     * Get the plain text's hash<br>
     * <B>Example:</B><br>
     * Hash hash = new hash();<br>
     * hash.encryption("this is a test text",ToolsConfig.MD5);
     *
     * @param plainText <em>:A plain text string</em>
     * @return <B>String</B> <em>:Result</em>
     */
    public String encryption(String plainText, String mode) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            MessageDigest hash = MessageDigest.getInstance(mode);
            byte[] temp = hash.digest(plainText.getBytes());
            for (int count = 0; count < temp.length; count++) {
                String val = Integer.toHexString((int) temp[count] & 0xff);
                if (val.length() == 1) {
                    val = "0" + val;
                }
                stringBuilder.append(val);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
